package cn.edu.jxau.test;

import java.util.ArrayList;
import java.util.List;

/**
 * 边的数组实现无向图
 * 
 * 所需的空间与顶点数和边数成正比
 * 添加一条边所需的时间为常数
 * 获取与顶点v相邻的顶点需要遍历所有的边
 * 
 * @author 付大石
 */
public class Graph {

    public static void main(String[] args) {
        Graph g = new Graph(13);
        g.addEdge(0, 5);
        g.addEdge(4, 3);
        g.addEdge(0, 1);
        g.addEdge(9, 12);
        g.addEdge(6, 4);
        g.addEdge(5, 4);
        g.addEdge(0, 2);
        g.addEdge(11, 12);
        g.addEdge(9, 10);
        g.addEdge(0, 6);
        g.addEdge(7, 8);
        g.addEdge(9, 11);
        g.addEdge(5, 3);
        for (int i : g.adj(0)) {
            System.out.print(i + " ");
        }
    }

    /**
     * vertex 顶点数目
     */
    private final int v;

    /**
     * edge 边的数目
     */
    private int e;

    /**
     * 边的数组
     */
    private List<Edge> edgeList;

    public Graph(int v) {

        this.v = v;
        edgeList = new ArrayList<>();
    }

    public int v() {
        return v;
    }

    public int e() {
        return e;
    }

    public void addEdge(int v, int w) {

        if (v >= this.v) {
            throw new IllegalArgumentException("顶点不存在，v=" + v);
        }
        if (w >= this.v) {
            throw new IllegalArgumentException("顶点不存在，w=" + w);
        }
        edgeList.add(new Edge(v, w));
        edgeList.add(new Edge(w, v));
        e++;
    }

    /**
     * 获取与顶点{@param v}相邻的的顶点
     * @param v
     * @return
     */
    public Iterable<Integer> adj(int v) {

        List<Integer> list = new ArrayList<>();
        for (Edge edge : edgeList) {
            if (edge.v == v) {
                list.add(edge.w);
            }
        }
        return list;
    }

    private class Edge {

        private int v;
        private int w;

        public Edge(int v, int w) {
            this.v = v;
            this.w = w;
        }
    }
}
